package club.cearnach.api.service.impl;

import club.cearnach.api.exception.UserException;
import club.cearnach.api.service.IUserService;
import club.cearnach.api.service.IVerificationCodeService;
import club.cearnach.security.vcode.exception.VerificationModeNotFoundException;
import club.cearnach.security.vcode.manager.VerificationCodeProcessorManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 阮胜
 * @date 2018/6/3 15:08
 */
@Service
@Slf4j
public class VerificationCodeServiceImpl implements IVerificationCodeService {
    private final IUserService userService;
    private final VerificationCodeProcessorManager verificationCodeProcessorManager;
    public VerificationCodeServiceImpl(IUserService userService, VerificationCodeProcessorManager verificationCodeProcessorManager) {
        this.userService = userService;
        this.verificationCodeProcessorManager = verificationCodeProcessorManager;
    }

    @Override
    public void createAndSend(HttpServletRequest request) throws VerificationModeNotFoundException, MessagingException, UserException {
        String account = request.getParameter("account");
        String email = request.getParameter("email");
        String vmode = request.getParameter("vmode");
        userService.findByAccountAndEmail(account, email).orElseThrow(() -> new UserException(UserException.USER_ACCOUNT_AND_EMAIL_CAN_NOT_MATCH));
        request.setAttribute("mailTo", email);
        verificationCodeProcessorManager.findVerificationCodeFactory(vmode).createAndSend(request);
    }

}
